package services

import (
	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/jinzhu/gorm"
	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/qor/qor"
	"github.com/xi3/qshop/Godeps/_workspace/src/github.com/qor/qor/admin"

	"github.com/xi3/qshop/models"
)

// Auth implements auth service
type Auth struct {
	Db gorm.DB
}

// LoginURL returns login URLAdmin
func (Auth) LoginURL(c *admin.Context) string {
	return "/login"
}

// LogoutURL returns logout URL
func (Auth) LogoutURL(c *admin.Context) string {
	return "/logout"
}

// GetCurrentUser get current user name from request cookie and retieve user information frome database
func (auth Auth) GetCurrentUser(c *admin.Context) qor.CurrentUser {
	if userid, err := c.Request.Cookie("userid"); err == nil {
		var user models.User
		//TODO: move DB related functions to models
		if !auth.Db.First(&user, "id = ?", userid.Value).RecordNotFound() {
			return &user
		}
	}
	return nil
}
